<?php


namespace app\backstage\logic;


use app\common\model\AuditorEvent;
use app\common\model\QuickApp as qa;
use app\common\model\RechargeItem;
use app\common\model\Recommend;
use think\Db;

class QaLogic
{


    /**
     * 设置App
     * @param $params
     * @return \think\response\Json
     */
    public function setQuickApp($params)
    {
        if (isset($params['id']) && $params['id']) {
            $qa = Qa::get($params['id']);
            if (!$qa) {
                return errJson('App不存在');
            }
            $qa->info->remarks = $params['remarks'];
            $qa->info->wx_payment_id = $params['wx_payment_id'];
            $qa->info->zfb_payment_id = $params['zfb_payment_id'];
			$qa->info->contact = $params['contact'];
            $qa->together('info')->save($params);
        } else {
            $qa = new qa();
            $item = $qa->getByPackageName($params['package_name']);
            if ($item) {
                return errJson('App包名已经存在');
            }
            Db::startTrans();
            try {
                $qa->save($params);
                $qa->info()->save([
                    'contact'           => $params['contact'],
                    'remarks'           => $params['remarks'],
                    'wx_payment_id'     => $params['wx_payment_id'],
                    'zfb_payment_id'    => $params['zfb_payment_id'],
                ]);

                /**
                 * 添加默认充值项
                 */
                $items = RechargeItem::defaultTemplate($qa->id);
                RechargeItem::insertAll($items);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return errJson($e->getMessage());
            }
        }
        return sucJson();
    }
}